/**
 * 
 */
package org.ycsoft.metroid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
 * @author Lookouster
 *
 */
public class RepoDownload extends Dialog{
	
	static String TAG="Metroid";
	Button btnClose, btnHide, btnCancel;
	ProgressBar prog;
	Handler handler;
	TextView state;
	private URL mapLink;
	private String cityMap;
	public URLConnection repoConnection;
	OutputStream mapLocalStream;
	InputStream mapRepoStream;
	boolean transferStarted=false, transferCompleted=false;
	File newMapFile;
	
	
	public RepoDownload(Context context){
		super(context);
	}
	
	public void setMapLink(URL url )
	{
		mapLink=url;
	}
	
	
	
	public void setCityMap(String s)
	{
		cityMap=s;
	}
	
	
	@Override
	public void onStart(){
		setContentView(R.layout.download);
		prog=(ProgressBar)findViewById(R.id.download_progress);
		state=(TextView) findViewById(R.id.txtState);
		btnCancel=(Button)findViewById(R.id.cancel);
		btnHide=(Button)findViewById(R.id.hide);
		this.setTitle(R.string.download);
		btnCancel.setOnClickListener(cancelListener);
		btnHide.setOnClickListener(hideListener);
		handler=new Handler();
		startDownload();
		
	}
	
	private View.OnClickListener closeListener=new View.OnClickListener()
	{
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if(transferStarted)
			try {
				mapLocalStream.close();
				mapRepoStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dismiss();
		}
	};
	
	private View.OnClickListener cancelListener=new View.OnClickListener()
	{
		public void onClick(View arg0)
		{
			if(transferStarted)
			try{
			mapLocalStream.close();
			mapRepoStream.close();
			newMapFile.delete();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			cancel();
		}
	};
	
	private View.OnClickListener hideListener=new View.OnClickListener()
	{
		public void onClick(View arg0)
		{
			//The dialog will just disappear; but download still in progress!!(as streams are not closed)
			dismiss();
		}
		
	};
	
	public void startDownload()
	{

			      new Thread(new Runnable()
			      {
			    	  public void run()
			    	  {
			    		  
			    		  getData();
			    	  }
			    	  }).start();
			      
	}
	
	public void getData()
	{
		//Should get here preferences map directory
		newMapFile=new File(Commons.PREFS_DEF_FOLDER, cityMap+Commons.MTD);
		try
		  {
		  int c=0,mStatus=0;
		  int progressStatus=0;
		  state.setText("Contacting the server");
		  repoConnection = mapLink.openConnection();
		  mapRepoStream = repoConnection.getInputStream();
		  transferStarted=true;
	      mapLocalStream=new FileOutputStream(newMapFile);
	      int i = repoConnection.getContentLength();
			while ((c = mapRepoStream.read()) != -1) 
			  {
				  mStatus++;
				  progressStatus=mStatus*100/i;				  
				  mapLocalStream.write(c);
				  showProgress(progressStatus, i,mStatus);
			  }
			transferCompleted=true;
			mapRepoStream.close();
		    mapLocalStream.close();
		      //btnHide.setClickable(false);
		      //btnClose.setClickable(true);
		      //btnCancel.setClickable(false);
		  }
		  catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e(TAG,"Unable to reach the server "+e.getMessage());
		  	}
		  btnClose=(Button)findViewById(R.id.close);
		  btnClose.setOnClickListener(closeListener);
	  
	}
	
	public void showProgress(final int progressStatus, final int total, final int mstatus)
	{
		synchronized(handler)
		  {
			  handler.post(new Runnable()
			  {
				  public void run()
				  {
					  state.setText(String.valueOf(progressStatus)+"% soit "+
							  String.valueOf(mstatus)+" sur "+String.valueOf(total));
					  prog.setProgress(progressStatus);
				  }
			  });
		  }
	}
}
